Ext.onReady(function() {
	Ext.SSL_SECURE_URL = "../../ext-3.2.1/resources/images/default/s.gif";
	Ext.BLANK_IMAGE_URL = "../../ext-3.2.1/resources/images/default/s.gif";
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';
	var pageSize = 20;
	// tab页面
    var centerTabPanel = new Ext.TabPanel({
        region : 'center',
        deferredRender : false,
        activeTab : 1,
        margins : '0 5 0 0',
        id:'centerTabPanelOrg',
       // plugins : new Ext.ux.TabCloseMenu(),
        resizeTabs : false,
        minTabWidth : 50,
        //tabWidth : 230,

        enableTabScroll : true,
        autoScroll : true,
         items:[{
            title: '下级标签：',
           // tabWidth:120,
           iconCls: 'tabsDown',
          //contentEl:'grid-div',
            disabled:true
           // autoScroll:true
        },
          {
            title: '会员信息管理',
            iconCls: 'tabs',
             //tabWidth:150,
            contentEl:'grid-div',
            autoScroll:true
        }],
        loadPage : function(href, cls, title) {
            var tabId = 'workPanel' + cls;
            var tab = this.getComponent(tabId);
            if (tab) {
                this.setActiveTab(tab);
            } else {
                var autoLoad = {
                    url : href,
                    scripts : true
                };
                var p = this.add(new DocPanel({
                    id : tabId,
                    cclass : cls,
                    layout : 'fit',
                    items : [new IFrameComponent({
                        id : tabId,
                        url : href
                    })],
                    title : title,
                    iconCls : 'tabs'
                }));
                this.setActiveTab(p);
            }
        }
    });
    IFrameComponent = Ext.extend(Ext.BoxComponent, {
        onRender : function(ct, position) {
            this.el = ct.createChild({
                tag : 'iframe',
                id : 'iframe-' + this.id,
                frameBorder : 0,
                src : this.url
            });
        }
    });
    DocPanel = Ext.extend(Ext.Panel, {
        closable : true,
        autoScroll : true,
        initComponent : function() {
            DocPanel.superclass.initComponent.call(this);
        },
        scrollToMember : function(member) {
            var el = Ext.fly(this.cclass + '-' + member);
            if (el) {
                var top = (el.getOffsetsTo(this.body)[1])
                        + this.body.dom.scrollTop;
                this.body.scrollTo('top', top - 25, {
                    duration : .75,
                    callback : this.hlMember.createDelegate(this, [member])
                });
            }
        },
        scrollToSection : function(id) {
            var el = Ext.getDom(id);
            if (el) {
                var top = (Ext.fly(el).getOffsetsTo(this.body)[1])
                        + this.body.dom.scrollTop;
                this.body.scrollTo('top', top - 25, {
                    duration : .5,
                    callback : function() {
                        Ext.fly(el).next('h2').pause(.2).highlight('#8DB2E3', {
                            attr : 'color'
                        });
                    }
                });
            }
        },
        hlMember : function(member) {
            var el = Ext.fly(this.cclass + '-' + member);
            if (el) {
                el.up('tr').highlight('#cadaf9');
            }
        }
    });
	
	new Ext.Viewport({
		region : 'center',
		layout : 'fit',
		items : centerTabPanel
	});
	var queryButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/query.png",
		id : 'queryButton',
		cls : 'x-btn-text-icon',
		text : '查询',
		tooltip : '查询记录',
		handler : onQueryClick
	});

	var addButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/add.png",
		id : 'addButton',
		cls : 'x-btn-text-icon',
		text : '添加',
		tooltip : '添加一条新的记录',
		// disabled:true,
		handler : onAddClick
	});
	var modButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/edit.png",
		id : 'modButton',
		cls : 'x-btn-text-icon',
		text : '修改',
		// disabled:true,
		tooltip : '修改一条选中记录。',
		handler : onModClick
	});
	var delButton = new Ext.Toolbar.Button({
		icon : "../../ext-3.2.1/examples/shared/icons/fam/del.png",
		id : 'delButton',
		cls : 'x-btn-text-icon',
		text : '删除',
		// disabled:true,
		tooltip : '删除已选中的记录。',
		handler : onDelClick
	});
		
	 //显示操作按钮
	function renderBtn_inputMember(val, p, record) {
		var contentId = Ext.id();
		createGridButton.defer(1, this, [1, "病历信息维护", contentId, record]);
		return ('<div id="' + contentId + '"></div>');
	}
	
	// 通用的列表中按钮生成函数
	function createGridButton(index, value, contentid, record) {
		if (index == 1) {			
			if(document.getElementById(contentid)) {			
				new Ext.Button({
					renderTo : contentid,
					text : "病历信息维护",
					handler : function(btn, e) {
						var ridStr = record.id;
						var idcard = record.data['id'];
						centerTabPanel.loadPage('../organization/caseList.jsp?idcard='+idcard, ridStr, value);
					},
					cls : 'x-btn-text',
					scope : this
				});
			}
		}
	}		
		

	var gridStore = new Ext.data.Store({
		proxy : new Ext.data.ScriptTagProxy({
			url : encodeURI('../../member/searchMemberList.action?category=2')
		}),
		reader : new Ext.data.JsonReader({
			root : 'results',
			totalProperty : 'total',
			id : 'id'
		}, [{
			name : 'id',
			mapping : 'id'
		},{
			name : 'username',
			mapping : 'username'
		}, {
			name : 'email',
			mapping : 'email'
		}, {
			name : 'realName',
			mapping : 'realName'
		}, {
			name : 'phone',
			mapping : 'phone'
		}, {
			name : 'idcard',
			mapping : 'idcard'
		}, {name: 'lock', mapping: 'lock'}
		,  {name: 'districtId', mapping: 'districtId'},
		  {name: 'category', mapping: 'category'},
		  {name: 'password', mapping: 'password'},
		   {name: 'sex', mapping: 'sex'}
		]),
		remoteSort : false
	});

	var sm = new Ext.grid.CheckboxSelectionModel();

	var cm = new Ext.ux.grid.LockingColumnModel([sm, {
		id : 'username',
		header : "登录名",
		dataIndex : 'username',
		width : 180,
		align : 'center',
		sortable : false,
		locked : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'email',
		header : "邮箱",
		dataIndex : 'email',
		width : 180,
		align : 'center',
		sortable : false
	}, {
		id : 'realName',
		header : "真实姓名",
		dataIndex : 'realName',
		align : 'center',
		width : 80,
		sortable : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'phone',
		header : "手机号码",
		dataIndex : 'phone',
		align : 'center',
		width : 120,
		sortable : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	}, {
		id : 'idcard',
		header : "身份证",
		dataIndex : 'idcard',
		align : 'center',
		width : 180,
		sortable : false,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	},{
		id : '',
		header : "病历信息维护",
		dataIndex : '',
		align : 'center',
		width : 100,
		sortable : false,
		renderer : renderBtn_inputMember,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;'
	},
       {
            id: 'password',
            header: "密码",
            dataIndex: 'password',
            align:'center',
            hidden:true,
            sortable: false
          
        },
       {
            id: 'lock',
            header: "锁住",
            dataIndex: 'lock',
            align:'center',
            hidden:true,
            sortable: false
        },
       {
            id: 'districtId',
            header: "区域",
            dataIndex: 'districtId',
            align:'center',
            hidden:true,
            sortable: false
          
        },
       {
            id: 'category',
            header: "类型",
            dataIndex: 'category',
            align:'center',
            hidden:true,
            sortable: false
          
        },
       {
            id: 'sex',
            header: "性别",
            dataIndex: 'sex',
            align:'center',
            hidden:true,
            sortable: false
          
        },
         {
            id: 'id',
            header: "userId",
            dataIndex: 'id',
            align:'center',
            hidden:true,
            sortable: false
          
        }
	]);
	
	var loginName = new Ext.form.TextField({
		fieldLabel : '登入名',
		id : 'loginName',
		name : 'loginName',
		width : 100,
		maxLength : 50,
		maxLengthText : "最大长度50"
	});

	// var grid = new Ext.grid.LockingGridPanel({
	var grid = new Ext.ux.grid.SSNJLOCKPAGEGrid({
		// el:'grid-div',
		id : 'grid',
		layout : 'fit',
		store : gridStore,
		loadMask : {
			msg : '正在加载数据，请稍候……'
		},
		cm : cm,
		height : gridHeight,
		sm : sm,
		viewConfig : {
			enableRowBody : false

		},
		bodyStyle : 'width:100%;',
		tbar : ['登录名：', loginName, '-', queryButton, '-',
				modButton, '-', delButton, '-', '&nbsp;&nbsp;&nbsp;&nbsp;'],
		frame : false,
		border : false,
		stripeRows : true
			// bbar:pagingToolbar
	});
	grid.render(Ext.get('grid-div'));
	gridStore.load({params:{start:0, limit:pageSize}});

	var formPanel;
	var win;
	function onAddClick(item) {
		var loginName, mail, realName, mobile,idcard,tempId,haveUser,category,groupText,dictinId,sex;
		var record, id, titleStr, loginNameValue,emailValue,nameValue,phoneValue,codeValue,lockValue,
		categoryValue,passValue,disValue,sexValue;
		titleStr = '增加记录'
		id = "";
		loginNameValue = "";
		emailValue = "";
		nameValue ="";
		phoneValue ="";
		codeValue ="";
		lockValue ="";
		categoryValue="";
		passValue="";
		disValue ="";
        sexValue ="";
		if (item == 'mod') {
			titleStr = '修改记录'
			var selectedCount = sm.getCount();
			if (selectedCount == 0) {
				Ext.Msg.alert('修改记录', '未选中任何一条记录，请选择要修改的记录！');
				return;
			} else if (selectedCount > 1) {
				Ext.Msg.alert('修改记录', '只能选择一条记录，不能同时选择多条记录！');
				return;
			}
			record = sm.getSelected();
			id = record.id;
			loginNameValue =  record.data['username'];
			emailValue =  record.data['email'];
			nameValue = record.data['realName'];
			phoneValue = record.data['phone'];
			codeValue = record.data['idcard'];
			lockValue =record.data['lock'];
		    categoryValue=record.data['category'];
		    passValue=record.data['password'];
		    disValue =record.data['districtId'];
            sexValue =record.data['sex'];		
		}
         
          tempId= new Ext.form.Hidden({
                fieldLabel: 'flag',
                name: 'tempId',
                width:100,
                maxLength:30,
                value:id
            });
             haveUser= new Ext.form.Hidden({
                fieldLabel: '是否开通帐号',
                name: 'tsSysuser.lock',
                width:100,
                maxLength:30,
                maxLengthText:"最大长度30",
                value:lockValue,
                allowBlank:true
            });
             category= new Ext.form.Hidden({
                fieldLabel: '会员身份',
                name: 'tsSysuser.category',
                width:100,
                maxLength:30,
                style : 'color:blue;cursor:not-allowed',
                maxLengthText:"最大长度30",
                value:categoryValue,
                allowBlank:true
            });
              groupText=new Ext.form.Hidden({
                fieldLabel: '密码',
                name: 'tsSysuser.password',
                width:100,
                maxLength:30,
                maxLengthText:"最大长度30",
                value:passValue
            });
            sex=new Ext.form.Hidden({
                fieldLabel: '性别',
                name: 'tmMember.sex',
                width:100,
                maxLength:30,
                maxLengthText:"最大长度30",
                value:sexValue
            });
            dictinId=new Ext.form.Hidden({
                fieldLabel: '地区',
                name: 'tmMember.districtId',
                width:100,
                maxLength:30,
                maxLengthText:"最大长度30",
                value:disValue
            });
		loginName = new Ext.form.TextField({
			fieldLabel : '登录名',
			id : 'code',
			name : 'tsSysuser.username',
			style : 'color:blue;cursor:not-allowed',
			readOnly : true,
			width : 200,
			maxLength : 30,
			maxLengthText : "最大长度10",
			value : loginNameValue,
			allowBlank : true
		});
         mail = new Ext.form.TextField({
                fieldLabel: '电子邮箱',
                id:'mail',
                name: 'tmMember.email',
                width:200,
                // regex : /^([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/,
                vtype : 'email',
                maxLength:30,
                value:emailValue,
                vtype:'email',
                maxLengthText:"最大长度30"
            }); 
            mailChangeFlag= new Ext.form.Hidden({
                name: 'mailChangeFlag',
                width:100,
                maxLength:30,
                value : 0
            }); 
		mail.on('change',function(){
			mailChangeFlag.setValue('1');
		});
		realName = new Ext.form.TextField({
			fieldLabel : '真实姓名',
			id : 'realName',
			name : 'tmMember.realName',
			regex : /^[\u4e00-\u9fa5]+$/,
			width : 200,
			maxLength : 5,
			maxLengthText : "最大长度5",
			value : nameValue,
			allowBlank : true
		});
		 mobile = new Ext.form.TextField({
                fieldLabel: '手机号码',
                id:'mobile',
                name: 'tmMember.phone',
                readOnly : true,
                value:phoneValue,
                style : 'color:blue;cursor:not-allowed',
                width:200,
                maxLength:16,
                maxLengthText:"最大长度16"
            });
		idcard = new Ext.form.TextField({
			fieldLabel : '身份证',
			id : 'idcard',
			name : 'tmMember.idcard',
			width : 200,
			maxLength : 18,
			style : 'color:blue;cursor:not-allowed',
			readOnly : true,
			maxLengthText : "最大长度18",
			value : codeValue,
			allowBlank : true
		});
		if (formPanel != null) {
			formPanel.destroy(true);
			formPanel = null;
		}
		if (!formPanel) {
			formPanel = new Ext.FormPanel({
				labelAlign : 'right',
				labelWidth : 125,
				url : '../../member/updateMemberInfo.action',
				frame : false,
				bodyStyle : 'padding:5px 5px 0',
				items : [mailChangeFlag,tempId,haveUser,category,groupText,loginName,sex, mail,dictinId, realName,mobile, idcard]
			});
		}
		if (win != null) {
			win.destroy(true);
			win = null;
		}
		if (!win) {
			win = new Ext.Window({
				id : 'formWin',
				title : titleStr,
				border : false,
				width : 500,
				height : 250,
				minWidth : 200,
				maximizable : false,
				closeAction : 'hide',
				layout : 'fit',
				plain : false,
				closable : true,
				modal : false,
				bodyStyle : 'padding:5px;',
				buttonAlign : 'center',
				items : formPanel,
				buttons : [{
					handler : function() {
						if (formPanel.getForm().isValid()) {
							if(realName.getValue()==''){
				            	Ext.Msg.alert('提示','请填写真实姓名');
				            	return false
				            }
							if(idcard.getValue()==''){
				            	Ext.Msg.alert('提示','请填写身份证');
				            	return false
				            }
							formPanel.getForm().submit({
								waitMsg : '正在处理，请稍等...',
								reset : true,
								failure : function(form, action) {
									Ext.MessageBox.hide();
									Ext.Msg.show({
										title : '错误',
										msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
												+ action.result.msg + '</span>',
										buttons : Ext.MessageBox.OK,
										icon : Ext.MessageBox.WARNING
									});
									// win.hide();
									// gridStore.reload();
								},
								success : function(form, action) {
									Ext.MessageBox.hide();
									Ext.Msg.show({
										title : '成功',
										msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
												+ action.result.msg + '</span>',
										buttons : Ext.MessageBox.OK,
										icon : Ext.MessageBox.INFO
									});

									win.hide();
									gridStore.reload();
								},
								method : 'POST'
							});
						}
					},
					text : '保存'
				}, {
					handler : function() {
						win.hide();
					},
					text : '取消'
				}]
			});
		}
		win.show();
	}
	
	function onModClick(item) {
		onAddClick('mod')
	}

	function startWith(str1, str2) {
		if (str2 == null || str2 == "" || str1.length == 0
				|| str2.length > str1.length)
			return false;
		if (str1.substr(0, str2.length) == str2)
			return true;
		else
			return false;
	}

	// 停用地区
	function onStopClick(item) {
		var selectedCount = sm.getCount();
		if (selectedCount == 0) {
			Ext.Msg.alert('停用操作', '未选中要停用的地区，请选择要停用的数据！');
			return;
		} else {
			var records = sm.getSelections();
			var _ids = '';
			for (var i = 0; i < records.length; i++) {
				if (records[i].data['canDel'] == false
						&& curYear == combo.getValue()) {
					Ext.Msg.alert('停用操作', '该地区下已经设有管辖的单位不能进行停用！');
					return;
				}
			}

			Ext.Msg.confirm('停用记录', '请确定要停用该地区吗？按是将当前系统中停用该地区！', function(btn) {
				if (btn == 'yes') {
					var records = sm.getSelections();
					var _ids = '';
					for (var i = 0; i < records.length; i++) {
						_ids += records[i].id;
						// alert(records[i].data['canDel']);
						_ids += '_';
					}
					Ext.MessageBox.wait('正在处理，请稍等...');

					Ext.Ajax.request({
						url : '../../district/stopDistrict.action',
						failure : function(result, request) {
							var responseArray = Ext.util.JSON
									.decode(result.responseText);
							Ext.MessageBox.hide();
							Ext.Msg.show({
								title : '错误',
								msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
										+ action.result.msg + '</span>',
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.WARNING
							});
						},
						success : function(result, request) {
							var responseArray = Ext.util.JSON
									.decode(result.responseText);
							Ext.MessageBox.hide();
							Ext.Msg.show({
								title : '成功',
								msg : '<span style="text-align:center;width:250px;margin:5 0 5 0;">'
										+ responseArray.msg + '</span>',
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.INFO
							});
							gridStore.reload();
						},
						params : {
							deleteID : _ids,
							districtYear : combo.value
						}
					});
				}
			});
		}
	}
	function onDelClick(item) {
		  var selectedCount = sm.getCount();
        if (selectedCount == 0) {
            Ext.Msg.alert('删除操作', '未选中要删除的数据，请选择要删除的数据！');
            return;
        } else { 
             var records = sm.getSelections();
            var _ids = '';
            
            Ext.Msg.confirm('删除记录', '请确认要删除记录吗?按是将删除选中记录！', function(btn) {
                if (btn == 'yes') {
                    var records = sm.getSelections();
                    var _ids = '';
                    for (var i = 0; i < records.length; i++) {
                        _ids += records[i].id;
                        _ids += '_';
                    }
                    Ext.MessageBox.wait('正在处理，请稍等...');
                    Ext.Ajax.request({
                        url:  '../../member/delMember.action',
                        failure: function(result, request) {
                            Ext.MessageBox.hide();
                            Ext.Msg.show({
                                title: '错误',
                                msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + '删除失败！' + '</span>',
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.WARNING
                            });
                        },
                        success: function(result, request) {
                            Ext.MessageBox.hide();
                            Ext.Msg.show({
                                title: '成功',
                                msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + '删除成功！' + '</span>',
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.INFO
                            });
                             gridStore.reload();
                            
                        },
                        params: { deleteID: _ids}
                    });
                }
            });
        }
	}

	function onQueryClick(item) {
		gridStore.proxy = new Ext.data.ScriptTagProxy({
			url : encodeURI('../../member/searchMemberList.action?category=2&loginName='
					+  encodeURI(loginName.getValue()))
		});
		gridStore.reload({
			params : {
				start : 0,
				limit : pageSize
			}
		});
	}
})
